import PateoSearchForm from '@/components/common/PateoSearchForm';
import { filterAuth } from '@/support/common';
import { PlusOutlined } from '@ant-design/icons';
import { Button, Card, message, Table } from 'antd';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import PropTypes from 'prop-types';
import React, { PureComponent } from 'react';
import { AddModal } from './Modal/addModal';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import { ColumnsType } from 'antd/es/table';
import { SelectDataModal } from './Modal/selectDataModal';
import { router } from 'umi';
@connect((state: any) => ({
  dataClassManagementDetail: state.dataClassManagementDetail,
  loading: state.loading.effects['dataClassManagementDetail/postFetchPage'],
}))
export default class classDetail extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
  };
  state = {
    formValues: {},
    formData: {},
    selectDataModalVisable: false,
    addModalVisible: false,
  };
  componentDidMount() {
    this.fetchPage();
  }
  handleFreshCurrentPage = () => {
    const {
      dataClassManagementDetail: {
        pageData: { pagination },
      },
    } = this.props;
    this.handleTableChange(pagination);
  };
  closeModal = (refresh = false as string | boolean) => {
    this.setState({
      addModalVisible: false,
      selectDataModalVisable: false,
      formData: {},
    });
    if (refresh == 'edit') {
      this.handleFreshCurrentPage();
    } else if (refresh == 'add') {
      this.fetchPage();
    }
  };
  handleTableChange = (pagination: any, filters: any = {}) => {
    const { formValues } = this.state;
    const { current, pageSize } = pagination;
    const params = {
      number: current,
      size: pageSize,
      ...formValues,
      ...filters,
    };
    this.fetchPage(params);
  };
  fetchPage = (params: any = {}) => {
    const { dispatch } = this.props;
    const {
      location: { query },
    } = this.props;
    params.dataClassId = query.id;
    dispatch({
      type: 'dataClassManagementDetail/postFetchPage',
      payload: { url: '/dataheader/list', ...params },
    });
  };
  render() {
    const { addModalVisible, formData, selectDataModalVisable } = this.state;
    const {
      dataClassManagementDetail: {
        pageData: { list, pagination },
      },
      location: { query },
      loading,
      dispatch,
    } = this.props;
    routerRedux;
    const columns: ColumnsType<any> = [
      {
        title: '序号',
        dataIndex: 'rowNumber',
        width: 40,
      },
      {
        title: '数据对象',
        dataIndex: 'dataObj',
        width: 150,
      },
      {
        title: '字段名称',
        dataIndex: 'fieldName',
        width: 150,
      },
      {
        title: '自定义类别（表头1）',
        dataIndex: 'dataCagHeader',
        width: 150,
      },
      {
        title: '自定义名称（表头2）',
        dataIndex: 'fieldNameHeader',
        width: 150,
      },
      {
        title: '操作',
        dataIndex: '操作',
        width: 120,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '修改表头',
              key: 'edit',
              auth: 'classDetail-opt',
              onConfirm: () => {
                this.setState({ addModalVisible: true });
              },
            },
            {
              title: '删除',
              key: 'del',
              auth: 'classDetail-opt',
              Popconfirm: true,
              message: `确认删除?`,
              onConfirm: () => {
                dispatch({
                  type: 'dataClassManagSelectDataModal/postObjWithRes',
                  payload: {
                    url: '/dataheader/delete',
                    id: record.id,
                  },
                  callback: res => {
                    if (res.statusCode === '0') {
                      message.success('删除成功');
                      this.handleFreshCurrentPage();
                    }
                  },
                });
              },
            },
          ];

          // btns.push(revokeBtn);
          return <PateoAuthButtons btns={btns} pathname={this.props.location.pathname} />;
        },
      },
    ];

    const paginationProps = {
      pageSizeOptions: [10, 20, 50],
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };
    const searchItems = [
      {
        type: 'input',
        title: '数据字段',
        key: 'search',
        placeholder: '请输入对象、类别或字段名称',
      },
    ];
    return (
      <div>
        <Card bordered={false}>
          {/* search form */}
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'dataClassManagementDetail/postFetchPage',
              url: '/dataheader/list',
            }}
            extraArgs={{
              dataClassId: query.id,
            }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
          />
        </Card>

        <Card style={{ marginTop: 12 }} bordered={false}>
          {/* add */}
          <div>
            {filterAuth(
              'classDetail-opt',
              this.context.permissions,
              this.props.location.pathname,
            ) ? (
              <div className="my_newItem">
                <Button
                  type="primary"
                  size="small"
                  onClick={() => this.setState({ selectDataModalVisable: true })}
                >
                  选择数据字段
                </Button>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => {
                    router.push(
                      '/connectPlat/vehicleConditionDataManagement/dataClassificationManagement',
                    );
                  }}
                >
                  返回
                </Button>
              </div>
            ) : null}
          </div>

          {/* table */}
          <Table
            size={'small'}
            rowKey={record => record.sid}
            dataSource={list}
            loading={loading}
            columns={columns}
            pagination={paginationProps}
            onChange={this.handleTableChange}
            scroll={{ x: 'auto' }}
            onRow={record => ({
              onClick: () => this.setState({ formData: record }),
            })}
          />
        </Card>
        <SelectDataModal
          modalVisible={selectDataModalVisable}
          closeModal={this.closeModal}
          formData={formData}
          location={this.props.location}
        />
        <AddModal modalVisible={addModalVisible} closeModal={this.closeModal} formData={formData} />
      </div>
    );
  }
}
